<html>
<head><title>Calculator</title></head>
<body>

<h1>Calculator</h1>
by Jay Chen <br />
Type an expression in the following box (e.g., 10.5+20*3/25).
<p>
<form method="GET">
<input type="text" name="expr"><input type="submit" value="Calculate">
</form>
</p>
<ul>
<li>Only numbers and +,-,* and / operators are allowed in the expression.
<li>The evaluation follows the standard operator precedence.
<li>The calculator does not support parentheses.
<li>The calculator handles invalid input "gracefully". It does not output PHP error messages.
</ul>
Here are some(but not limit to) reasonable test cases:
<ol>
  <li> A basic arithmetic operation:  3+4*5=23 </li>
  <li> An expression with floating point or negative sign : -3.2+2*4-1/3 = 4.46666666667, 3+-2.1*2 = -1.2 </li>
  <li> Some typos inside operation (e.g. alphabetic letter): Invalid input expression 2d4+1 </li>
</ol>

<?php

//Here, we take in our value from the input text box
$param = $_GET["expr"];

//We test to make sure an input was given
if ($param)
{
	//We are taking out all spare spaces
	$temp = "";
	for ($i = 0; $i < strlen($param); $i++)
	{
		if ($param[$i] != ' ' && $param[$i] != '\t')
			$temp = $temp . $param[$i];
	}
	$param = $temp;

	//A valid bit to check if we should be giving an eval result
	$valid = 1;

	//Display the Result header
	print "<h2>Result</h2>";

	//Creating our regular expression
	$pattern = '/^([-]?[0-9]+\.?[0-9]*[\+\-\*\/]?)*([-]?[0-9]+\.?[0-9]*)$/';
	
	//A hard coded way to check for "--" error
	if (preg_match("/--/", $param) == 1)
	{
		print "Invalid input expression $param.";
		$valid = 0;
	}

	// A hard coded way to look for letters
	else if (preg_match('/[a-zA-Z]/', $param) == 1)
	{
		print "Invalid input expression $param.";
		$valid = 0;
	}

	// Applying our regular expression
	else if (preg_match($pattern, $param) == 0)
	{
		print "Invalid input expression $param.";
		$valid = 0;
	}

	// Given we haven't outputted a bad expression output, we call eval
	if ($valid == 1)
	{
		$str = "";
		@eval("\$str = $param;");
		print "$param" . " = " . "$str";
	}

}

?>

</body>
</html>
